import React, {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {View, StyleSheet, FlatList, Text, TouchableOpacity} from 'react-native';
import {useBottomTabBarHeight} from '@react-navigation/bottom-tabs';
import {ScreenHeight, ScreenWidth, videos,usableScreenHeight} from '../../config/devices';
import Video from 'react-native-video';
import {CollectionIcon, NextIcon, FullScreenIcon} from '../../kit/icon';
import {useModalContext} from '../../context/ModalContext';
import {useAppContext} from '../../context/AppContext';
import {BasicText, FoldText} from '../../kit/text';
import {EpisodesTag} from '../../kit/Tag';
import {normalize} from '../../utils/adapter';

type IconProps = {
  color?: string;
};

const CollectionView = React.memo(({color = '#fff'}: IconProps) => {
  return (
    <TouchableOpacity style={_styles.collectionView}>
      <CollectionIcon color={color} />
      <Text style={[_styles.text, {color}]}>收藏</Text>
    </TouchableOpacity>
  );
});

const NextView = React.memo(({onPass}: {onPass: () => void}) => {
  return (
    <TouchableOpacity style={_styles.collectionView} onPress={onPass}>
      <NextIcon />
      <Text style={[_styles.text]}>下一集</Text>
    </TouchableOpacity>
  );
});

const FullScreen = React.memo(({onPass}: {onPass: () => void}) => {
  return (
    <TouchableOpacity style={_styles.collectionView} onPress={onPass}>
      <FullScreenIcon />
      <Text style={[_styles.text]}>选集</Text>
    </TouchableOpacity>
  );
});

const PlayLeftScreen = React.memo(() => {
  const [currentIndex, setCurrrentIndex] = useState<number>(0);
  const videoRefs = useRef([]);
  const tabBarHeight = useBottomTabBarHeight();
  // const insets = useSafeAreaInsets();

  const onViewableItemsChanged = useRef(
    ({viewableItems}: {viewableItems: Array<any>}) => {
      if (viewableItems.length > 0) {
        const index = viewableItems[0].index;
        setCurrrentIndex(index);
      }
    },
  ).current;

  const viewConfigRef = useRef({
    waitForInteraction: true,
    viewAreaCoveragePercentThreshold: 95,
  }).current;

  const EpisodesInfo = React.memo(() => {
    return (
      <View style={_styles.episodes_info_view}>
        <View style={_styles.episodes_name_view}>
          <BasicText color="#fff" fontSize={normalize(18)}>
            剧集信息
          </BasicText>
          <EpisodesTag />
        </View>
        <View style={_styles.episodes_content_view}>
          <FoldText width={normalize(ScreenWidth / 3)} />
        </View>
      </View>
    );
  });

  const VideoItem = React.memo(
    ({
      item,
      index,
      tabBarHeight,
    }: {
      item: any;
      index: number;
      tabBarHeight: number;
    }) => {
      const [isPause, setIsPause] = useState(false);
      const [isLoading, setIsLoading] = useState(true);
      const [_, setIsBuffering] = useState(false);
      const modalCtx = useModalContext();
      const appCtx = useAppContext();


      useEffect(() => {
        if (!isLoading) {
          appCtx?.setStatusBarStyles('light-content');
        } else {
          appCtx?.setStatusBarStyles('dark-content');
        }
      }, [isLoading]);

      const height = useMemo(() => ScreenHeight - (tabBarHeight + usableScreenHeight), [tabBarHeight]);

      const handlePauseOrPlay = useCallback(() => {
        if (!isPause) {
          setIsPause(true);
        } else {
          setIsPause(false);
        }
      }, [isPause]);

      const handleNextEpisode = useCallback(() => {
        modalCtx?.showModal('RewardsModal');
      }, []);

      const handleSelectEpisodes = useCallback(() => {
        modalCtx?.showModal('EpisodesModal', 'fade', {video: 1} as any);
      }, []);

      return (
        <TouchableOpacity
          activeOpacity={1}
          onPress={handlePauseOrPlay}
          style={[_styles.videoContainer, {height: height}]}>
          {isLoading ? (
            <View style={_styles.coverImage}>
              <Text>加载中...</Text>
            </View>
          ) : null}
          <Video
            ref={ref => {
              (videoRefs.current[index] as unknown as any) = ref;
            }}
            source={{uri: item.url}}
            style={{height:height,width:'100%'}}
            resizeMode={'cover'}
            paused={isPause ? isPause : currentIndex !== index}
            repeat
            onLoad={() => setIsLoading(false)}
            onBuffer={({isBuffering}) => setIsBuffering(isBuffering)}
          />
          <View style={_styles.operation_view}>
            <CollectionView color={item.isColletion ? 'red' : '#fff'} />
            <NextView onPass={handleNextEpisode} />
            <FullScreen onPass={handleSelectEpisodes} />
          </View>
          <EpisodesInfo />
        </TouchableOpacity>
      );
    },
  );
  return (
    <View>
      <FlatList
        data={videos}
        renderItem={item => (
          <VideoItem
            item={item.item}
            index={item.index}
            tabBarHeight={tabBarHeight}
          />
        )}
        keyExtractor={item => item.id.toString()}
        pagingEnabled
        showsVerticalScrollIndicator={false}
        onViewableItemsChanged={onViewableItemsChanged}
        viewabilityConfig={viewConfigRef}
        snapToInterval={ScreenHeight - (tabBarHeight + usableScreenHeight)}
        decelerationRate="fast"
      />
    </View>
  );
});

const _styles = StyleSheet.create({
  videoContainer: {
    justifyContent: 'center',
    alignItems: 'center',
    position: 'relative',
    backgroundColor:'red',
    borderBottomColor:'#fff',
    borderBottomWidth:1,
  },
  operation_view: {
    position: 'absolute',
    right: normalize(17),
    bottom: normalize(200),
    zIndex: 100,
  },
  collectionView: {
    marginTop: normalize(30),
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
  },
  text: {
    color: '#fff',
    fontSize: normalize(10),
  },
  coverImage: {
    position: 'absolute',
    width: ScreenWidth,
    height: ScreenHeight,
    zIndex: 120,
    backgroundColor: '#fff',
    justifyContent: 'center',
    alignItems: 'center',
  },
  episodes_info_view: {
    position: 'absolute',
    left: normalize(0),
    bottom: normalize(0),
    width: normalize(ScreenWidth - 30),
    zIndex: 110,
    padding: normalize(15),
  },
  episodes_name_view: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: normalize(14),
  },
  episodes_content_view: {
    marginTop: normalize(14),
    marginBottom: normalize(13),
  },
});

export default PlayLeftScreen;
